/* Copyright (c) 2007-2008, Jeffrey R Griffin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*     * Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in the
*       documentation and/or other materials provided with the distribution.
*     * Neither the name of Jeffrey R Griffin nor the
*       names of his contributors may be used to endorse or promote products
*       derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY Jeffrey R Griffin ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package net.visibleblue.android.app.dynamic;

import java.io.FileNotFoundException;

import android.app.Activity;
import android.content.Intent;
import android.content.Resources;
import android.content.Resources.Theme;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.Window;
import android.view.WindowManager;

public class HostCanvas extends Activity {

	private static final String SUBACT = "SubActivityClass";
	private DynamicActivity _dynamicActivity = null;
	private Resources.Theme _theme = null;
	private int _themeResource = -1;

	@Override
	protected void onCreate(Bundle icicle) {
		loadDynamicActivity();
		_dynamicActivity.onCreate(icicle);
		super.onCreate(icicle);
	}

	@Override
	protected void applyThemeResource(Theme theme, int resid, boolean first) {
		loadDynamicActivity();
		if(_themeResource==-1)
			theme.applyStyle(android.R.style.Theme_White, true);
		else
			theme.applyStyle(_themeResource, true);
		_dynamicActivity.applyThemeResource(theme, resid, first);
		if(first)
		{
			CharSequence title = _dynamicActivity.getTitle();
			if(title!=null)
				setTitle(title);
			else
				requestWindowFeature(Window.FEATURE_NO_TITLE);
		}
	}

	@Override
	public Resources.Theme getTheme()
	{
		boolean first = false;
		if(_theme==null)
		{
			first = true;
			_theme = _dynamicActivity.getResources().newTheme();
			if(_themeResource==-1)
				_themeResource = _dynamicActivity.getThemeResource();
		}
		applyThemeResource(_theme, _themeResource, first);
		return _theme;
	}

	private void loadDynamicActivity()
	{
		if(_dynamicActivity==null)
		{
			String className = null;
			Intent intent = getIntent();
			if(intent!=null)
				className = (String)intent.getExtra(SUBACT);
			else
				className = DynamicActivityHost._urlApkPM.getTempActivityName();
			if(className!=null)
				loadDynamicActivity(className);
			else
			{
				Class clazz = null;
				try
				{
					clazz = DynamicActivityHost._urlApkPM.getURLClass();
				}
				catch(ClassNotFoundException cnfEx)
				{
					//TODO: test handling
					throw new RuntimeException(cnfEx);
				}
				loadDynamicActivity(clazz);
			}
		}
	}

	private void loadDynamicActivity(String className)
	{
		if(_dynamicActivity==null)
		{
			Class clazz = null;
			try
			{
				clazz = DynamicActivityHost._urlApkPM.getClassInPackage(className);
			}
			catch(ClassNotFoundException cnfEx)
			{
				//TODO: test handling
				throw new RuntimeException(cnfEx);
			}
			loadDynamicActivity(clazz);
		}
	}

	private void loadDynamicActivity(Class clazz)
	{
		if(_dynamicActivity==null)
		{
			try
			{
				_dynamicActivity = (DynamicActivity)clazz.newInstance();
			}
			catch(IllegalAccessException illEx)
			{
				//TODO: test handling
				throw new RuntimeException(illEx);
			}
			catch(InstantiationException instEx)
			{
				//TODO: test handling
				throw new RuntimeException(instEx);
			}
			try
			{
				_dynamicActivity.inject(this, clazz.getName().substring(0, 
						clazz.getName().lastIndexOf(".")), 
						DynamicActivityHost._urlApkPM.getCachedPackagePath(),
						DynamicActivityHost._urlApkPM.getClassLoader());
			}
			catch(FileNotFoundException fnfEx)
			{
				//TODO: test handling
				throw new RuntimeException(fnfEx);
			}
		}
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if(_dynamicActivity!=null && 
				_dynamicActivity.dispatchKeyEvent(event))
			return true;
		return super.dispatchKeyEvent(event);
	}

	@Override
	protected void onCompleteThaw(Bundle state) {
		if(_dynamicActivity!=null)
			_dynamicActivity.onCompleteThaw(state);
		super.onCompleteThaw(state);
	}

	@Override
	public void onContentChanged() {
		if(_dynamicActivity!=null)
			_dynamicActivity.onContentChanged();
		super.onContentChanged();
	}

	@Override
	public CharSequence onCreateDescription() {
		CharSequence chars = null;
		if(_dynamicActivity!=null)
			chars = _dynamicActivity.onCreateDescription();
		if(chars!=null)
			return chars;
		else return super.onCreateDescription();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if(_dynamicActivity!=null && 
				_dynamicActivity.onCreateOptionsMenu(menu))
			return true;
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) {
		if(_dynamicActivity!=null && 
				_dynamicActivity.onCreateThumbnail(outBitmap, canvas))
			return true;
		return super.onCreateThumbnail(outBitmap, canvas);
	}

	@Override
	protected void onDestroy() {
		if(_dynamicActivity!=null)
			_dynamicActivity.onDestroy();
		super.onDestroy();
	}

	@Override
	protected void onFreeze(Bundle outState) {
		if(_dynamicActivity!=null)
			_dynamicActivity.onFreeze(outState);
		super.onFreeze(outState);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(_dynamicActivity!=null && 
				_dynamicActivity.onKeyDown(keyCode, event))
			return true;
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if(_dynamicActivity!=null && 
				_dynamicActivity.onKeyUp(keyCode, event))
			return true;
		return super.onKeyUp(keyCode, event);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		if(_dynamicActivity!=null)
			_dynamicActivity.onNewIntent(intent);
		super.onNewIntent(intent);
	}

	@Override
	public boolean onOptionsItemSelected(Menu.Item item) {
		if(_dynamicActivity!=null && 
				_dynamicActivity.onOptionsItemSelected(item))
			return true;
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onPause() {
		if(_dynamicActivity!=null)
			_dynamicActivity.onPause();
		super.onPause();
	}

	@Override
	protected void onPostCreate(Bundle icicle) {
		if(_dynamicActivity!=null)
			_dynamicActivity.onPostCreate(icicle);
		super.onPostCreate(icicle);
	}

	@Override
	protected void onPostResume() {
		if(_dynamicActivity!=null)
			_dynamicActivity.onPostResume();
		super.onPostResume();
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		if(_dynamicActivity!=null && 
				_dynamicActivity.onPrepareOptionsMenu(menu))
			return true;
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	protected void onResume() {
		if(_dynamicActivity!=null)
			_dynamicActivity.onResume();
		super.onResume();
	}

	@Override
	protected void onRestart() {
		if(_dynamicActivity!=null)
			_dynamicActivity.onRestart();
		super.onRestart();
	}

	@Override
	protected void onStart() {
		if(_dynamicActivity!=null)
			_dynamicActivity.onStart();
		super.onStart();
	}

	@Override
	protected void onStop() {
		if(_dynamicActivity!=null)
			_dynamicActivity.onStop();
		super.onStop();
	}

	@Override
	public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
		if(_dynamicActivity!=null)
			_dynamicActivity.onWindowAttributesChanged(params);
		super.onWindowAttributesChanged(params);
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		if(_dynamicActivity!=null)
			_dynamicActivity.onWindowFocusChanged(hasFocus);
		super.onWindowFocusChanged(hasFocus);
	}

	@Override
	public void startSubActivity(Intent intent, int requestCode) {
		if(intent.getComponent().getPackageName().equals(_dynamicActivity.getPackageName()))
		{
			String className = intent.getComponent().getClassName();
			intent.setClassName(this, HostCanvas.class.getName());
			intent.putExtra(SUBACT, className);
			DynamicActivityHost._urlApkPM.storeTempActivityName(className);
		}
		super.startSubActivity(intent, requestCode);
	}

}
